using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Services;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace WinformDevFramework
{
    public partial class Frmw_Sale : BaseForm1
    {
        private Iw_SaleServices _w_SaleServices;
        private Iw_CustomerServices _w_CustomerServices;
        private Iw_SaleDetailServices _w_SaleDetailServices;
        private IW_GoodsServices _w_GoodsServices;
        private Iw_SaleReturnServices _w_SaleReturnServices;
        private Iw_SaleOutWarehouseServices _w_SaleOutWarehouseServices;
        private ISysUserServices _w_SysUserServices;
        public Frmw_Sale(Iw_SaleServices w_SaleServices, Iw_CustomerServices w_CustomerServices, Iw_SaleDetailServices w_SaleDetailServices, IW_GoodsServices w_GoodsServices, Iw_SaleReturnServices w_SaleReturnServices, Iw_SaleOutWarehouseServices w_SaleOutWarehouseServices,ISysUserServices sysUserServices)
        {
            _w_SaleServices = w_SaleServices;
            InitializeComponent();
            _w_CustomerServices = w_CustomerServices;
            _w_SaleDetailServices = w_SaleDetailServices;
            _w_GoodsServices = w_GoodsServices;
            _w_SaleReturnServices = w_SaleReturnServices;
            _w_SaleOutWarehouseServices = w_SaleOutWarehouseServices;
            _w_SysUserServices= sysUserServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["CustomerCode"].HeaderText = "客户编码";
            this.dataGridViewList.Columns["InvoicesDate"].HeaderText = "单据日期";
            this.dataGridViewList.Columns["MakeUserID"].Visible = false;
            this.dataGridViewList.Columns["DeliveryDate"].HeaderText = "交货日期";
            this.dataGridViewList.Columns["SaleCode"].HeaderText = "单据编号";
            this.dataGridViewList.Columns["InvoicesFile"].Visible = false;
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["TotalPrice"].HeaderText = "总金额";
            this.dataGridViewList.Columns["TotalPrice1"].HeaderText = "已结金额";
            this.dataGridViewList.Columns["TotalPrice2"].HeaderText = "未结金额";
            this.dataGridViewList.Columns["CustomerName"].HeaderText = "客户名称";

            //设置客户下拉
            CustomerName.DataSource = _w_CustomerServices.Query();
            CustomerName.DisplayMember = "CustomerName";
            CustomerName.ValueMember = "CustomerCode";
            CustomerName.SelectedIndexChanged += CustomerName_SelectedIndexChanged;

            //设置商品
            GoodsName.DataSource = _w_GoodsServices.Query();
            GoodsName.DisplayMember = "GoodsName";
            GoodsName.ValueMember = "GoodsCode";

            MakeUser.DataSource = _w_SysUserServices.Query();//值查找销售部门
            MakeUser.ValueMember = "ID";
            MakeUser.DisplayMember = "Fullname";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        private void CustomerName_SelectedIndexChanged(object? sender, EventArgs e)
        {
            CustomerCode.Text = CustomerName.SelectedValue.ToString();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_Sale;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.CustomerCode.Text = model.CustomerCode;
            this.InvoicesDate.Text = model.InvoicesDate.ToString();
            this.MakeUser.SelectedValue = model.MakeUserID;
            this.DeliveryDate.Text = model.DeliveryDate.ToString();
            this.SaleCode.Text = model.SaleCode;
            this.InvoicesFile.Text = model.InvoicesFile;
            this.Remark.Text = model.Remark;
            this.TotalPrice.Text = model.TotalPrice.ToString();
            this.TotalPrice1.Text = model.TotalPrice1.ToString();
            this.TotalPrice2.Text = model.TotalPrice2.ToString();
            this.CustomerName.SelectedValue = model.CustomerCode;

            SetDataToDetail(GetDetailData(model.SaleCode));
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            CustomerCode.Text = _w_CustomerServices.Query().First().CustomerCode;
            MakeUser.SelectedValue = AppInfo.User.ID;
            TotalPrice1.ReadOnly = true;
            TotalPrice2.ReadOnly = true;
            TotalPrice.ReadOnly = true;
            dataGridViewDetail.Rows.Clear();
            SetDataGridViewReadonlyStatus();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            if (CheckData(SaleCode.Text))
            {
                base.EditFunction(sender, e);
                SetToolButtonStatus(formStatus);
                TotalPrice1.ReadOnly = true;
                TotalPrice2.ReadOnly = true;
                TotalPrice.ReadOnly = true;
                SetDataGridViewReadonlyStatus();
            }

        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_Sale model = new w_Sale();
                    // TODO获取界面的数据
                    model.CustomerCode = this.CustomerCode.Text;
                    model.InvoicesDate = this.InvoicesDate.Value;
                    model.MakeUserID = this.MakeUser.SelectedValue.ToInt32();
                    model.DeliveryDate = this.DeliveryDate.Value;
                    if (string.IsNullOrEmpty(this.SaleCode.Text))
                    {
                        model.SaleCode = $"XS{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.SaleCode = this.SaleCode.Text;
                    }

                    model.InvoicesFile = this.InvoicesFile.Text;
                    model.Remark = this.Remark.Text;
                    model.TotalPrice = this.TotalPrice.Text.ToDecimal();
                    model.TotalPrice1 = 0;
                    model.TotalPrice2 = model.TotalPrice;
                    model.CustomerName = this.CustomerName.Text;

                    //明细数据
                    List<w_SaleDetail> details = new List<w_SaleDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_SaleDetail detail = new w_SaleDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsName"].Value.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.UnitPrice = row.Cells["UnitPrice"].FormattedValue.ToDecimal();
                            detail.DiscountPrice = row.Cells["DiscountPrice"].FormattedValue.ToDecimal();
                            detail.TotalPrice = row.Cells["TotalPriceD"].FormattedValue.ToDecimal();
                            detail.TaxRate = row.Cells["TaxRate"].FormattedValue.ToDecimal();
                            detail.TaxUnitPrice = row.Cells["TaxUnitPrice"].FormattedValue.ToDecimal();
                            detail.TaxPrice = row.Cells["TaxPrice"].FormattedValue.ToDecimal();
                            detail.TotalTaxPrice = row.Cells["TotalTaxPrice"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            details.Add(detail);
                        }
                    }
                    int id = _w_SaleServices.AddSaleInfo(model, details);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        SaleCode.Text = model.SaleCode;
                        SetDataToDetail(GetDetailData(model.SaleCode));
                    }

                }
                // 修改
                else
                {
                    w_Sale model = _w_SaleServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.CustomerCode = this.CustomerCode.Text;
                    model.InvoicesDate = this.InvoicesDate.Value;
                    model.MakeUserID = this.MakeUser.SelectedValue.ToInt32();
                    model.DeliveryDate = this.DeliveryDate.Value;
                    model.SaleCode = this.SaleCode.Text;
                    model.InvoicesFile = this.InvoicesFile.Text;
                    model.Remark = this.Remark.Text;
                    model.TotalPrice = this.TotalPrice.Text.ToDecimal();
                    model.TotalPrice1 = this.TotalPrice1.Text.ToDecimal();
                    model.TotalPrice2 = this.TotalPrice2.Text.ToDecimal();
                    model.CustomerName = this.CustomerName.Text;


                    //明细数据
                    List<w_SaleDetail> details = new List<w_SaleDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_SaleDetail detail = new w_SaleDetail();
                            detail.SaleCode = row.Cells["SaleCodeD"].FormattedValue.ToString();
                            detail.SaleDetailCode = row.Cells["SaleDetailCode"].FormattedValue.ToString();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsName"].Value.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.UnitPrice = row.Cells["UnitPrice"].FormattedValue.ToDecimal();
                            detail.DiscountPrice = row.Cells["DiscountPrice"].FormattedValue.ToDecimal();
                            detail.TotalPrice = row.Cells["TotalPriceD"].FormattedValue.ToDecimal();
                            detail.TaxRate = row.Cells["TaxRate"].FormattedValue.ToDecimal();
                            detail.TaxUnitPrice = row.Cells["TaxUnitPrice"].FormattedValue.ToDecimal();
                            detail.TaxPrice = row.Cells["TaxPrice"].FormattedValue.ToDecimal();
                            detail.TotalTaxPrice = row.Cells["TotalTaxPrice"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            details.Add(detail);
                        }
                    }
                    if (_w_SaleServices.UpdateSaleInfo(model, details))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.SaleCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            SetDataToDetail(GetDetailData(SaleCode.Text));

        }

        public override void DelFunction(object sender, EventArgs e)
        {
            if (CheckData(SaleCode.Text))
            {
                base.DelFunction(sender, e);
                var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    _w_SaleServices.DeleteById(Int32.Parse(txtID.Text));
                    _w_SaleDetailServices.Delete(p => p.SaleCode == SaleCode.Text);
                    formStatus = FormStatus.Del;
                    SetToolButtonStatus(formStatus);
                    //列表重新赋值
                    dataGridViewDetail.Rows.Clear();
                    this.dataGridViewList.DataSource = GetData();
                }
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_Sale> GetData()
        {
            List<w_Sale> data = new List<w_Sale>();
            data = _w_SaleServices.Query();
            return data;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_SaleDetail> GetDetailData(string code)
        {
            List<w_SaleDetail> data = new List<w_SaleDetail>();
            data = _w_SaleDetailServices.QueryListByClause(p => p.SaleCode == code);
            return data;
        }
        /// <summary>
        /// 明细表 设置数据
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_SaleDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["Number"].Value = p.Number;
                row.Cells["GoodsName"].Value = p.GoodsCode;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["UnitPrice"].Value = p.UnitPrice;
                row.Cells["DiscountPrice"].Value = p.DiscountPrice;
                row.Cells["TotalPriceD"].Value = p.TotalPrice;
                row.Cells["TaxRate"].Value = p.TaxRate;
                row.Cells["TaxUnitPrice"].Value = p.TaxUnitPrice;
                row.Cells["TaxPrice"].Value = p.TaxPrice;
                row.Cells["TotalTaxPrice"].Value = p.TotalTaxPrice;
                row.Cells["RemarkD"].Value = p.Remark;
                row.Cells["TotalTaxPrice"].Value = p.TotalTaxPrice;
                row.Cells["SaleCodeD"].Value = p.SaleCode;
                row.Cells["SaleDetailCode"].Value = p.SaleDetailCode;
            });
        }

        private void dataGridViewDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "GoodsName" && dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsName"].Value != null)
                {
                    var model = _w_GoodsServices.QueryByClause(p => p.GoodsCode == dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsName"].Value);
                    dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsCode"].Value = dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsName"].Value;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsSpec"].Value = model.GoodsSpec;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsUnit"].Value = model.GoodsUnit;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["Number"].Value = 0;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["UnitPrice"].Value = 0;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TotalPriceD"].Value = 0;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TaxRate"].Value = 0;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["DiscountPrice"].Value = 0;

                    dataGridViewDetail.Rows[e.RowIndex].Cells["TaxUnitPrice"].Value = 0;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TaxPrice"].Value = 0;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TotalTaxPrice"].Value = 0;

                }

                //数量
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "Number" || dataGridViewDetail.Columns[e.ColumnIndex].Name == "UnitPrice" || dataGridViewDetail.Columns[e.ColumnIndex].Name == "DiscountPrice" || dataGridViewDetail.Columns[e.ColumnIndex].Name == "TaxRate")
                {
                    decimal value = dataGridViewDetail.Rows[e.RowIndex].Cells["Number"].Value == null ? 0 : dataGridViewDetail.Rows[e.RowIndex].Cells["Number"].Value.ToDecimal();
                    //购货单价
                    decimal unitPrice = dataGridViewDetail.Rows[e.RowIndex].Cells["UnitPrice"].Value == null ? 0 : dataGridViewDetail.Rows[e.RowIndex].Cells["UnitPrice"].Value.ToDecimal();
                    //折扣金额
                    decimal discountPrice = dataGridViewDetail.Rows[e.RowIndex].Cells["DiscountPrice"].Value == null ? 0 : dataGridViewDetail.Rows[e.RowIndex].Cells["DiscountPrice"].Value.ToDecimal();
                    //税率
                    decimal taxRate = dataGridViewDetail.Rows[e.RowIndex].Cells["TaxRate"].Value == null
                        ? 0
                        : dataGridViewDetail.Rows[e.RowIndex].Cells["TaxRate"].Value.ToDecimal() / 100;

                    decimal jine = value * unitPrice - discountPrice;
                    //金额
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TotalPriceD"].Value = jine;

                    decimal danjia = unitPrice * (1 + taxRate);

                    //含税单价
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TaxUnitPrice"].Value = danjia;

                    //税额
                    decimal shuie = unitPrice * (taxRate) * value - discountPrice * taxRate;
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TaxPrice"].Value = shuie;

                    //含税金额
                    dataGridViewDetail.Rows[e.RowIndex].Cells["TotalTaxPrice"].Value =
                        shuie + jine;
                    SetFormTotalData();
                }
            }
        }
        private void SetFormTotalData()
        {
            decimal total = 0;
            foreach (DataGridViewRow row in dataGridViewDetail.Rows)
            {
                if (!row.IsNewRow)
                {
                    total += row.Cells["TotalTaxPrice"].Value.ToDecimal();
                }
            }
            TotalPrice.Text = total.ToString();
        }
        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "GoodsName", "Number", "RemarkD", "UnitPrice", "TaxRate", "DiscountPrice" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }
        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns></returns>
        private bool CheckData(string code)
        {
            //是否有退货记录
            if (_w_SaleReturnServices.Exists(p => p.SaleCode == code))
            {
                MessageBox.Show("该销售单有退货记录，不能操作！", "提示");
                return false;
            }
            //是否有出库记录
            if (_w_SaleOutWarehouseServices.Exists(p => p.SaleCode == code))
            {
                MessageBox.Show("该销售单有出库记录，不能操作！", "提示");
                return false;
            }
            return true;
        }
    }
}
